package com.zj.leetcode.medium.stack;

import java.util.Stack;

/**
 * @program: algorithm
 * @description: 逆波兰表达式求值
 * 150 evaluate-reverse-polish-notation
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class EvaluateReversePolishNotation {
    public static void main(String[] args) {
//        String[] tokens = {"2","1","+","3","*"};
//        String[] tokens = {"4","13","5","/","+"};
        String[] tokens = {"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
        Solution solution = new EvaluateReversePolishNotation().new Solution();
        System.out.println(solution.evalRPN(tokens));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<Integer>();
            for (int i = 0; i < tokens.length; i++) {
                switch (tokens[i]) {
                    case "+":
                        if (stack.size() >= 2) {
                            stack.push(stack.pop() + stack.pop());
                        }
                        break;
                    case "-":
                        if (stack.size() >= 2) {
                            Integer sub1 = stack.pop();
                            Integer sub2 = stack.pop();
                            stack.push(sub2 - sub1);
                        }
                        break;
                    case "*":
                        if (stack.size() >= 2) {
                            stack.push(stack.pop() * stack.pop());
                        }
                        break;
                    case "/":
                        if (stack.size() >= 2) {
                            Integer div1 = stack.pop();
                            Integer div2 = stack.pop();
                            stack.push(div2 / div1);
                        }
                        break;
                    default:
                        stack.push(Integer.valueOf(tokens[i]));
                }

            }

            return stack.size() > 0 ? stack.pop() : 0;

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
